package com.goods.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.OutStockService;
import com.goods.common.model.business.*;
import com.goods.common.vo.business.OutStockDetailVO;
import com.goods.common.vo.business.OutStockVO;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author XiaoHong
 * @description 发放记录接口
 * @date 2022/2/18
 */
@Service
public class OutStockServiceImpl implements OutStockService {
    @Autowired
    private OutStockMapper outStockMapper;

    //发放记录列表
    @Override
    public PageVO<OutStockVO> findOutStockList(OutStockVO outStockVO, Integer pageNum, Integer pageSize) {
        //http://www.localhost:8989/business/outStock/findOutStockList?
        // pageNum=1&pageSize=10&status=0&outNum=123456677&type=0
        PageHelper.startPage(pageNum, pageSize);
        Integer status = 0;
        String outNum = null;
        Integer type = null;
        if (outStockVO != null) {
            status = outStockVO.getStatus();
            outNum = outStockVO.getOutNum();
            type = outStockVO.getType();
        }
        List<OutStockVO> outStockList = outStockMapper.findOutStockList(status, outNum, type);
        PageInfo<OutStockVO> listPageInfo = new PageInfo<OutStockVO>(outStockList);

        return new PageVO<>(listPageInfo.getTotal(), outStockList);
    }

    //获取出库记录明细
    @Override
    public OutStockDetailVO detail(Long id, Integer pageNum) {

        PageHelper.startPage(pageNum, 3);
        OutStockDetailVO detail = outStockMapper.detail(id);
//        PageInfo<OutStockDetailVO> listPageInfo = new PageInfo(outStockDetailVOList);
//        return new PageVO<>(listPageInfo.getTotal(),outStockDetailVOList);
        return detail;
    }

    @Autowired
    private ConsumeMapper consumeMapper;

    @Override
    public void addOutStock(OutStockVO outStockVo, String username) {
        OutStock outStock = new OutStock();

        //判断是否新增的来源
        if (outStockVo.getConsumerId() == null) {
            Supplier supplier = new Supplier();

            Consumer consumer = new Consumer();
            consumer.setAddress(outStockVo.getAddress());
//            supplier.setAddress(inStockVO.getAddress());
            consumer.setName(outStockVo.getName());
            consumer.setContact(outStockVo.getContact());
            consumer.setPhone(outStockVo.getPhone());
            consumer.setSort(outStockVo.getSort());
            consumer.setCreateTime(new Date());
            consumer.setModifiedTime(new Date());
            consumeMapper.insert(consumer);
            System.out.println(consumer);
            //设置提供者id
            outStock.setConsumerId(consumer.getId());
        } else {

            //设置提供者id
            outStock.setConsumerId(outStockVo.getConsumerId());
        }
        Consumer consumer = consumeMapper.selectByPrimaryKey(outStockVo.getConsumerId());

        //设置入库单号
        String uuid = UUID.randomUUID().toString();
        outStock.setOutNum(uuid);
        //捐赠类型
        outStock.setType(outStockVo.getType());
        //设置操作员  //TODO 这里应该设置当前用户的名称，现在先将就着admin
        outStock.setOperator(username);
        //创建时间
        outStock.setCreateTime(new Date());

        //捐赠数量(物资总量)
        List<Object> productList = outStockVo.getProducts();
        List<Map<String, Integer>> productListOk = new ArrayList<>();
        for (Object o : productList) {
//            Map n = (Map)o; 转
            String jsonString = JSON.toJSONString(o);
            HashMap<String, Integer> map = JSON.parseObject(jsonString, HashMap.class);
            productListOk.add(map);
        }
//        //进行类型转换
//        List<Map<String, Integer>> productListOk = productList.stream().map(product -> {
//            HashMap<String,Integer> map = JSON.parseObject((String) product, HashMap.class) ;
//            return map;
//        }).collect(Collectors.toList());
//

        Integer productNumberTotal = 0;
        for (Map<String, Integer> map : productListOk) {
            OutStockInfo outStockInfo = new OutStockInfo();

            //插入到关联表
            outStockInfo.setOutNum(outStock.getOutNum());
            outStockInfo.setCreateTime(new Date());
            outStockInfo.setModifiedTime(new Date());
            //获取每一个商品的数量
            Integer productNumber = map.get("productNumber");
            productNumberTotal += productNumber;
            //设置关联表中的数据
            outStockInfo.setProductNumber(productNumber);
            //根据productid主键获取product信息
            Product product = productMapper.selectByPrimaryKey(map.get("productId"));
            outStockInfo.setPNum(product.getPNum());
            outStockInfoMapper.insert(outStockInfo);
        }
        //捐赠数量(物资总量)
        outStock.setProductNumber(productNumberTotal);
        //设置默认状态 待审核状态 2
        outStock.setStatus(2);
        //设置备注
        outStock.setRemark(outStockVo.getRemark());
        outStock.setPriority(outStockVo.getPriority());
        outStockMapper.insert(outStock);

        System.out.println(outStockVo);
    }

    //将出库单删除
    @Override
    public void delete(Long outStockId) {
        //获取iNUm
        OutStock outStock = outStockMapper.selectByPrimaryKey(outStockId);
        String outNum = outStock.getOutNum();
        //删除info相关关联
        Example example = new Example(OutStockInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("outNum", outNum);
        int i = outStockInfoMapper.deleteByExample(example);
        System.out.println("i:" + i);
        //删除instock表下的此数据
        outStockMapper.deleteByPrimaryKey(outStockId);
    }

    //将出库信心移入到回收站
    @Override
    public void remove(Long outStockId) {
        OutStock outStock = new OutStock();
        outStock.setId(outStockId);
        outStock.setStatus(1);
        outStockMapper.updateByPrimaryKeySelective(outStock);
    }

    //从回收站恢复
    @Override
    public void back(Long outStockId) {
        OutStock outStock = new OutStock();
        outStock.setId(outStockId);
        outStock.setStatus(0);
        outStockMapper.updateByPrimaryKeySelective(outStock);

    }

    @Autowired
    ProductStockMapper productStockMapper;

    @Override
    public void publish(Long outStockId) {
        //将出库物资通过审核
        OutStock outStock = new OutStock();
        outStock.setId(outStockId);
        outStock.setStatus(0);
        outStockMapper.updateByPrimaryKeySelective(outStock);
        //同时更新库存物资数量
        OutStock outStock1 = outStockMapper.selectByPrimaryKey(outStockId);
        outStock1.getOutNum();
        //获取当前入库号下的商品编号
        Example example = new Example(OutStockInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("outNum", outStock1.getOutNum());
        List<OutStockInfo> outStockInfos = outStockInfoMapper.selectByExample(example);
        //根据商品编号和数量修改库存信息
        outStockInfos.forEach(inStockInfo -> {
            Example example1 = new Example(ProductStock.class);
            example1.createCriteria().andEqualTo("pNum", inStockInfo.getPNum());
            ProductStock productStock = productStockMapper.selectOneByExample(example1);
            if (productStock == null) {
                //说明新增的物资商品.之前并不存在。
                productStock.setPNum(inStockInfo.getPNum());
                productStock.setStock(Long.valueOf(inStockInfo.getProductNumber()));
                productStockMapper.insert(productStock);
            }
            productStock.setStock(inStockInfo.getProductNumber() - productStock.getStock());
            productStockMapper.updateByExample(productStock, example1);
        });

    }

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OutStockInfoMapper outStockInfoMapper;

}
